package com.elock.util;

import javax.jms.DeliveryMode;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TopicConnection;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQTopicPublisher;
import org.apache.activemq.ActiveMQTopicSession;
import org.apache.activemq.command.ActiveMQTopic;

import com.elock.base.core.util.PropertiesLoader;
import com.elock.ts.pojo.MessageTemporary;

public class MqUtil {

	/*** 连接ActiveMq的地址 */
	public static String MQ_URL;

	/*** 连接ActiveMq的用户名 */
	public static String MQ_NAME;

	/*** 连接ActiveMq的密码 */
	public static String MQ_PASSWORD;

	/*** ActiveMq发送消息的主题 */
	public static String MQ_TOPIC_NAME;

	private static class MqUtilHandler {
		private static MqUtil instance = new MqUtil();
	}

	public static MqUtil getInstance() {
		return MqUtilHandler.instance;
	}

	private MqUtil() {
		// 读取配置文件
		PropertiesLoader loader = new PropertiesLoader("/application.properties");
		MQ_URL = loader.getProperty("mqurl");
		MQ_NAME = loader.getProperty("connectuser");
		MQ_PASSWORD = loader.getProperty("connectpwd");
		MQ_TOPIC_NAME = loader.getProperty("topic");
	}

	/***
	 * 向ActiveMQ发送消息
	 * @param messageTemporary
	 * @throws Exception 
	 */
	public static void sendToMQ(MessageTemporary messageTemporary) throws Exception {

		getInstance();

		TopicConnection connection = null;
		ActiveMQTopicSession session = null;
		ActiveMQTopicPublisher publisher = null;
		try {
			/* 与MQ连接并发送信息 */
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					MQ_URL);
			connection = connectionFactory.createTopicConnection(MQ_NAME, MQ_PASSWORD);
			session = (ActiveMQTopicSession) connection.createTopicSession(false,
					Session.AUTO_ACKNOWLEDGE);
			ActiveMQTopic topic = (ActiveMQTopic) session.createTopic(MQ_TOPIC_NAME);
			publisher = (ActiveMQTopicPublisher) session.createPublisher(topic);
			publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
			connection.start();
			ObjectMessage objectMessage = session.createObjectMessage();
			objectMessage.setObject(messageTemporary);
			publisher.publish(objectMessage);
		}
		finally {
			if (publisher != null) {
				publisher.close();
			}
			if (session != null) {
				session.close();
			}
			if (connection != null) {
				connection.close();
			}
		}
	}

	public static void main(String[] args) throws Exception {

//		BIT15	允许关机
//		BIT14	立即关机
//		BIT13	重启系统
//		BIT12	单独重启GPS模块
//		BIT11	系统升级
//		BIT10	钥匙禁止使用
//		BIT9	钥匙恢复使用
		MessageTemporary temporary = new MessageTemporary();
		temporary.setTerminalNum("KY000019");
		temporary.setSim("13702239861");
		temporary.setOperationType(0x8600);
		temporary.setOperationContent("14");
		temporary.setProcessor("user");
		temporary.setMessageSendId(1L);

		sendToMQ(temporary);
	}
}
